# -*- coding: utf-8 -*-
import ast
from datetime import datetime
from Common.mysql import db
from Common.yaml_method import YamlMethod
from src.User.Database.user_database import User
from src.User.Database.user_database import UserSchema
from sqlalchemy import and_
from src.Bugs.Database.bugs_database import BugData, BugDataSchema
from sqlalchemy import func


class BugCount:

    def __init__(self):
        self.code = YamlMethod().read_data('code.yaml')['code']

    def base_bug_data(self, project_id, sprint):
        """
        统计项目迭代中的缺陷基础数据
        :param project_id:
        :param sprint:
        :return:
        """
        bugs_base_info = {
            "total_bugs": 0,
            "status_amount": {
                "resolved": 0,
                "unresolved": 0,
            },
            "bug_severity_amount": {
                "fatal": 0,
                "serious": 0,
                "normal": 0,
                "hint": 0,
                "suggestion": 0,
            },
            "bug_type": [
                {"name": '功能缺失', "value": 0},
                {"name": '技术缺陷', "value": 0},
                {"name": '用户体验不佳', "value": 0},
                {"name": 'UI实现偏差', "value": 0},
                {"name": '需求缺陷', "value": 0},
                {"name": '功能实现偏差', "value": 0},
            ],
            "bug_platform": [
                {"name": 'iOS', "value": 0},
                {"name": 'Android', "value": 0},
                {"name": 'server', "value": 0},
                {"name": 'Web&H5', "value": 0}
            ]
        }
        bugs = BugData.query.filter_by(projectId=project_id, sprint=sprint, delete=None).all()
        if bugs:
            bugs_base_info["total_bugs"] = len(bugs)
            for item in bugs:
                bug_data = BugDataSchema().dump(item)
                # bug状态数据汇总处理
                if bug_data["status"] == "已关闭":
                    bugs_base_info["status_amount"]["resolved"] = bugs_base_info["status_amount"]["resolved"] + 1
                else:
                    bugs_base_info["status_amount"]["unresolved"] = bugs_base_info["status_amount"]["unresolved"] + 1
                # bug严重程度数据汇总处理
                if bug_data["severity"] == "致命":
                    bugs_base_info["bug_severity_amount"]["fatal"] = bugs_base_info["bug_severity_amount"]["fatal"] + 1
                if bug_data["severity"] == "严重":
                    bugs_base_info["bug_severity_amount"]["serious"] = bugs_base_info["bug_severity_amount"]["serious"] + 1
                if bug_data["severity"] == "一般":
                    bugs_base_info["bug_severity_amount"]["normal"] = bugs_base_info["bug_severity_amount"]["normal"] + 1
                if bug_data["severity"] == "提示":
                    bugs_base_info["bug_severity_amount"]["hint"] = bugs_base_info["bug_severity_amount"]["hint"] + 1
                if bug_data["severity"] == "建议":
                    bugs_base_info["bug_severity_amount"]["suggestion"] = bugs_base_info["bug_severity_amount"]["suggestion"] + 1
                # bug类型数据汇总处理
                if bug_data["bugType"] == "功能缺失":
                    bugs_base_info["bug_type"][0]["value"] =  bugs_base_info["bug_type"][0]["value"] + 1
                if bug_data["bugType"] == "技术缺陷":
                    bugs_base_info["bug_type"][1]["value"] =  bugs_base_info["bug_type"][1]["value"] + 1
                if bug_data["bugType"] == "用户体验不佳":
                    bugs_base_info["bug_type"][2]["value"] =  bugs_base_info["bug_type"][2]["value"] + 1
                if bug_data["bugType"] == "UI实现偏差":
                    bugs_base_info["bug_type"][3]["value"] =  bugs_base_info["bug_type"][3]["value"] + 1
                if bug_data["bugType"] == "需求缺陷":
                    bugs_base_info["bug_type"][4]["value"] =  bugs_base_info["bug_type"][4]["value"] + 1
                if bug_data["bugType"] == "功能实现偏差":
                    bugs_base_info["bug_type"][5]["value"] =  bugs_base_info["bug_type"][5]["value"] + 1
                # bug所属平台数据汇总处理
                if bug_data["platform"] == "iOS":
                    bugs_base_info["bug_platform"][0]["value"] = bugs_base_info["bug_platform"][0]["value"] +1
                if bug_data["platform"] == "Android":
                    bugs_base_info["bug_platform"][1]["value"] = bugs_base_info["bug_platform"][1]["value"] +1
                if bug_data["platform"] == "Server":
                    bugs_base_info["bug_platform"][2]["value"] = bugs_base_info["bug_platform"][2]["value"] +1
                if bug_data["platform"] == "Web & H5":
                    bugs_base_info["bug_platform"][3]["value"] = bugs_base_info["bug_platform"][3]["value"] +1

        res = {
            'code': self.code[0],
            'message': 'success',
            'data': bugs_base_info
        }
        return res

    def development_bug_type(self, project_id, sprint, responsible):
        """
        查询单个用户的缺陷类型统计
        :param project_id:
        :param sprint:
        :param responsible:
        :return:
        """
        bug_type = [
            {"name": '功能缺失', "value": 0},
            {"name": '技术缺陷', "value": 0},
            {"name": '用户体验不佳', "value": 0},
            {"name": 'UI实现偏差', "value": 0},
            {"name": '需求缺陷', "value": 0},
            {"name": '功能实现偏差', "value": 0}
        ]
        if responsible == "All":
            bugs = BugData.query.filter_by(projectId=project_id, sprint=sprint, delete=None).all()
        else:
            bugs = BugData.query.filter_by(projectId=project_id, sprint=sprint, responsible=responsible, delete=None).all()
        if bugs:
            for item in bugs:
                bug_data = BugDataSchema().dump(item)
                if bug_data["bugType"] == "功能缺失":
                    bug_type[0]["value"] = bug_type[0]["value"] + 1
                if bug_data["bugType"] == "技术缺陷":
                    bug_type[1]["value"] =  bug_type[1]["value"] + 1
                if bug_data["bugType"] == "用户体验不佳":
                    bug_type[2]["value"] =  bug_type[2]["value"] + 1
                if bug_data["bugType"] == "UI实现偏差":
                    bug_type[3]["value"] =  bug_type[3]["value"] + 1
                if bug_data["bugType"] == "需求缺陷":
                    bug_type[4]["value"] =  bug_type[4]["value"] + 1
                if bug_data["bugType"] == "功能实现偏差":
                    bug_type[5]["value"] =  bug_type[5]["value"] + 1
        # 剔除为value 为 0 的数据
        bug_type_data = []
        for data in bug_type:
            if data["value"] != 0:
                bug_type_data.append(data)
        res = {
            'code': self.code[0],
            'message': 'success',
            'data': bug_type_data
        }
        return res

    def count_daily_bug(self, project_id, sprint):
        """
        按创建日期分组查询迭代bug数
        :param project_id:
        :param sprint:
        :return:
        """
        bugs = (db.session.query(func.date(BugData.create_time).label('date'), func.count(BugData.id).label('bug_count'))
                .filter_by(projectId=project_id, sprint=sprint, delete=None).group_by(func.date(BugData.create_time)).all())
        bug_data_info = {
            "dimensions": ["data", "缺陷数量"],
            "bug_data_list": [],
            "series": [{ "type": "bar" }]
        }
        for item in bugs:
            # 将 datetime 对象格式化成所需的字符串格式
            formatted_date = datetime.strptime(str(item.date), "%Y-%m-%d").strftime("%Y/%m/%d")
            bug_data_info["bug_data_list"].append({"data": formatted_date, "缺陷数量": item.bug_count})

        res = {
            'code': self.code[0],
            'message': 'success',
            'data': bug_data_info
        }
        return res

    def developer_bugs(self, project_id: int , sprint: str, development: list):
        """
        统计开发人员的bug数和bug reopen数
        :param project_id:
        :param sprint:
        :param development:
        :return:
        """
        if development:
            project_user = development
        else:
            # 查询项目组中的开发人员
            user_data = User.query.filter(
                and_(
                    User.roles == 'development',
                    (
                            User.user_projects.like(f'%{str(project_id)}%')
                    )
                )
            ).all()
            project_user = []
            for i in user_data:
                user_schema = UserSchema()
                user_info = user_schema.dump(i)
                if project_id in ast.literal_eval(user_info['user_projects']):
                    project_user.append(user_info['realName'])

        # 构建查询
        bugs = (
            db.session.query(
                BugData.responsible,
                func.count(BugData.id).label('bug_count'),
                func.sum(BugData.is_reopen).label('reopen_count')
            )
            .filter(
                BugData.responsible.in_(project_user),
                BugData.projectId == project_id,
                BugData.sprint == sprint,
                BugData.delete == None
            )
            .group_by(BugData.responsible)
            .all()
        )

        # 定义接口返回的统计数据格式
        bug_data_info = {
            "dimensions": ["data", "缺陷总数", "Reopen数"],
            "bug_data_list": [],
            "series": [{"type": "bar"}, {"type": "bar"}]
        }
        # 将查询的结果数据填充到接口返回数据中
        for item in bugs:
            bug_count = item.bug_count if item.bug_count is not None else 0
            reopen_count = item.reopen_count if item.reopen_count is not None else 0
            bug_data_info["bug_data_list"].append({"data": item.responsible, "缺陷总数": bug_count, "Reopen数": int(reopen_count)})
            project_user.remove(item.responsible)
        # 如果有没有产生缺陷数据的开发人员，则缺陷数据都赋值为0
        if project_user:
            for user in project_user:
                bug_data_info["bug_data_list"].append({"data": user, "缺陷总数": 0, "Reopen数": 0})
        res = {
            'code': self.code[0],
            'message': 'success',
            'data': bug_data_info
        }
        return res